﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Common.Library.Helper
{
    /// <summary>
    /// Des加解密算法助手类
    /// </summary>
    public class DesEncryptDecryptHelper
    {
        /// <summary>
        /// 私有秘钥
        /// </summary>
        public const string SecretKey = "Developer";

        /// <summary>
        /// DES 加密 注意:密钥必须为8位
        /// </summary>
        /// <param name="inputString">待加密字符串</param>
        /// <param name="encryptKey">密钥 
        /// <para>字符串超长将会被截断，提取前8位;长度不足将会从左至右依次补足;字符串为空将使用默认Key</para>
        /// </param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt(string inputString, string encryptKey)
        {
            string strRes = "";
            try
            {
                encryptKey = KeyDispose(encryptKey);
                byte[] byKey = null;
                byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                byKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.UTF8.GetBytes(inputString);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write))
                    {
                        cs.Write(inputByteArray, 0, inputByteArray.Length);
                        cs.FlushFinalBlock();
                        strRes = Convert.ToBase64String(ms.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return strRes;
        }

        /// <summary>
        /// DES 解密 注意:密钥必须为8位
        /// </summary>
        /// <param name="inputString">待解密字符串</param>
        /// <param name="decryptKey">
        /// 密钥 
        /// <para>字符串超长将会被截断，提取前8位;长度不足将会从左至右依次补足;字符串为空将使用默认Key</para>
        /// </param>
        /// <returns>解密后的字符串</returns>
        public static string Decrypt(string inputString, string decryptKey)
        {
            string strRes = "";
            try
            {
                decryptKey = KeyDispose(decryptKey);
                byte[] byKey = null;
                byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                byte[] inputByteArray = new Byte[inputString.Length];
                byKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(inputString);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write))
                    {
                        cs.Write(inputByteArray, 0, inputByteArray.Length);
                        cs.FlushFinalBlock();
                        strRes = Encoding.UTF8.GetString(ms.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return strRes;

        }

        /// <summary>
        /// Key处理 Key长度限定为8 Key必须为英文 Key不为英文将返回DefaultK
        /// <para>字符串超长将会被截断，提取前8位;长度不足将会从左至右依次补足;字符串为空将使用默认Key</para>
        /// </summary>
        /// <param name="strKey"></param>
        /// <returns></returns>
        private static string KeyDispose(string strKey)
        {
            string strRes = "";
            string strDefaultKey = "DefaultK";
            if (string.IsNullOrEmpty(strKey))
            {
                return strDefaultKey;
            }

            ////判断是否有非法字符
            Regex rex = new Regex(@"^[A-Za-z0-9_]+$");
            Match ma = rex.Match(strKey);
            if (!ma.Success)
            {
                return strDefaultKey;
            }

            if (strKey.Length > 8)
            {
                //Key长度大于8，进行截取
                strRes = strKey.Substring(0, 8);
            }
            else if (strKey.Length == 8)
            {
                strRes = strKey;
            }
            else
            {
                //Key长度小于8，进行循环读取
                List<char> listKeyChar = strKey.ToList();
                for (int i = 0, j = 0; i < 8; i++)
                {
                    j = i % listKeyChar.Count;
                    strRes += listKeyChar[j];
                }
            }
            return strRes;
        }
    }
}
